package com.fatcat.easybuy.exception;

import com.fatcat.easybuy.util.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 郝秦毅
 * @since 2025/9/10 15:23
 */
@RestControllerAdvice(basePackages = "com.fatcat.easybuy.controller")
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ResponseResult businessException(BusinessException e) {
        LOGGER.error("业务异常：{}", e.getMessage());
        return ResponseResult.error(e.getMessage());
    }

    // 异常处理器方法，处理LoginException
    @ExceptionHandler(LoginException.class)
    public ResponseResult loginException(LoginException e) {
        LOGGER.error("登录异常：{}", e.getMessage());

        // 判断异常中是否包含自定义错误码
        String code = e.getCode();
        if (code != null) {
            // 使用异常中携带的错误码
            return ResponseResult.error(code, e.getMessage());
        } else {
            // 如果没有自定义错误码，使用默认错误码（例如"LOGIN_ERROR"）
            return ResponseResult.error("LOGIN_ERROR", e.getMessage());
        }
    }

    //处理 @RequestParam 接收的对象校验失败
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseResult bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        LOGGER.error("参数校验失败：{}", errorMap);
        return ResponseResult.error("400", "参数校验失败").add("errorList", errorMap);
    }
}
